#pragma once
#include <vector>
#include "InetAddr.hpp"
#include "Mutex.hpp"
#include <string>
using namespace MutexMoudle;
class Route
{
private:
    bool isonline(InetAddr &peer)
    {
        for (auto &use : _online)
        {
            if (peer == use)
            {
                return true;
            }
        }
        return false;
    }
    void DeleteUser(InetAddr &use)
    {
        for (auto iter = _online.begin(); iter != _online.end(); iter++)
        {
            if (*iter == use)
            {
                LOG(LogLevel::INFO) << "删除一个在线用户:" << use.StringAddr() << "成功";
                _online.erase(iter);
                break;
            }
        }
    }

public:
    Route()
    {
    }
    void RouteMessage(int sockfd, std::string message, InetAddr &peer)
    {
        MutexMoudle::LockGuard lock(_mutex);
        if (!isonline(peer))
        {
            LOG(LogLevel::INFO) << "新增一个在线用户: " << peer.StringAddr();
            _online.push_back(peer);
        }
        
        std::string sendmessage = peer.StringAddr() + "#" + message;
        // 下面开始发消息
        LOG(LogLevel::INFO) << "转发消息: " << sendmessage;  // 添加日志
        for (auto &ch : _online)
        {
            int n = sendto(sockfd, sendmessage.c_str(), sendmessage.size(), 0, (sockaddr *)&ch.NetAddr(), ch.NetAddrLen());
        }

        if (message == std::string("QUIT"))
        {
            // 删除用户
            LOG(LogLevel::INFO) << "删除一个在线用户: " << peer.StringAddr();
            DeleteUser(peer);
        }
    }
    ~Route()
    {
    }

private:
    std::vector<InetAddr> _online;
   MutexMoudle::Mutex _mutex;
};